package org.luxor.commons.security.config;

import feign.RequestInterceptor;
import org.luxor.commons.security.component.FeignOauth2Interceptor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration;
import org.springframework.cloud.security.oauth2.client.AccessTokenContextRelay;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;

/**
 * feign 拦截器传递 header 中oauth token， 使用hystrix 的信号量模式
 *
 * @author Mr.Yan  @date: 2020/9/29
 */
@Configuration
@AutoConfigureAfter(OAuth2AutoConfiguration.class)
@ConditionalOnProperty("security.oauth2.client.client-id")
public class TokenRelayAutoConfiguration {

    @Bean
    public AccessTokenContextRelay accessTokenContextRelay(ObjectProvider<OAuth2ClientContext> context) {
        return new AccessTokenContextRelay(context.getIfAvailable());
    }

    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor(ObjectProvider<OAuth2ClientContext> context,
                                                            OAuth2ProtectedResourceDetails resource, ObjectProvider<AccessTokenContextRelay> accessTokenContextRelay) {
        return new FeignOauth2Interceptor(context.getIfAvailable(), resource, accessTokenContextRelay.getIfAvailable());
    }

}
